package com.hnhp.advice;

import cn.hutool.json.JSONUtil;
import com.hnhp.dto.ResponseDto;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
//接口增强器
@RestControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //默认不增强 需要打开
        return true;
    }

    @ExceptionHandler
    public Object processException(Exception ex){
        ResponseDto dto = ResponseDto.error(1,ex.getMessage());
        return dto;
    }


    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter methodParameter,
            MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse) {
        //解决双层包含
        if(body instanceof ResponseDto){
            return body;
        }


        ResponseDto dto = ResponseDto.success(body);
        // 解决返回string 字符串的问题
        if(aClass == StringHttpMessageConverter.class){
            return JSONUtil.toJsonStr(dto);
        }

        return dto;
    }
}
